package com.smartboot.plus.config;

import com.smartboot.plus.api.R;
import com.smartboot.plus.api.ResultCode;
import com.smartboot.plus.exception.ServiceException;
import tech.smartboot.feat.cloud.annotation.Bean;
import tech.smartboot.feat.cloud.annotation.InterceptorMapping;
import tech.smartboot.feat.core.common.HttpStatus;
import tech.smartboot.feat.router.Context;
import tech.smartboot.feat.router.Interceptor;

@Bean
public class RouteInterceptConfig {




    @InterceptorMapping("/*")
    public Interceptor interceptor() {
        return (context, completableFuture, chain) -> {
            try {
                String requestURI = context.Request.getRequestURI();
                // 放行静态资源和登录请求
                if (shouldSkipAuthCheck(requestURI)) {
                    chain.proceed(context, completableFuture);
                    return;
                }
                // 验证用户权限
                if (!checkUserPermission(context)) {
                    context.Response.setHttpStatus(HttpStatus.UNAUTHORIZED);
                    R.handleException(ResultCode.UN_AUTHORIZED.getMessage(), context.Response);
                    return;
                }
                chain.proceed(context, completableFuture);
            }  catch (ServiceException e) {
                context.Response.setHttpStatus(HttpStatus.BAD_REQUEST);
                R.handleException(e, context.Response);
                // e.printStackTrace();
            } catch (Exception e) {
                context.Response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
                R.handleException(ResultCode.INTERNAL_SERVER_ERROR.getMessage(), context.Response);
                e.printStackTrace();
            }

        };
    }

    /**
     * 判断是否需要跳过权限检查
     *
     * @param requestURI 请求URI
     * @return 是否需要跳过
     */
    private boolean shouldSkipAuthCheck(String requestURI) {
        return requestURI.endsWith(".css") || requestURI.endsWith(".js") || requestURI.endsWith(".json") ||
                requestURI.endsWith(".png") || requestURI.endsWith(".jpg") ||
                requestURI.endsWith(".ico") || requestURI.endsWith(".woff") ||
                requestURI.endsWith(".woff2") || requestURI.endsWith(".ttf") ||
                requestURI.equals("/auth/login") || requestURI.equals("/auth/logout")
                || requestURI.equals("/") || requestURI.startsWith("/api/");
    }

    /**
     * 检查用户权限
     *
     * @param context 请求上下文
     * @return 是否通过验证
     */
    private boolean checkUserPermission(Context context) {
        try {
            String s1 = context.session().get(context.session().getSessionId());
            if (s1 == null) {
                return false;
            }

            return true;
        } catch (Exception e) {

            return false;
        }
    }

}
